package lock.synchronize;

import serial.Student;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author zhangxin
 * @date 2020/9/22
 */
public class Test {
    Student student = new Student();

    public static void main(String[] args) {

        ArrayList<Object> objects = new ArrayList<>();
        Iterator<Object> iterator = objects.iterator();
        // moniterenter moniterexit
        Test test = new Test();

        new Thread(() -> {
            test.test();
        }).start();

        new Thread(() -> {
            test.test2();
        }).start();

        new Thread(() -> {
          synchronized (test) {
              try {
                  System.out.println(" synchronized (test) ");
                  Thread.sleep(1000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
        }).start();

        /*
        new Thread(() -> {
            test.test3();
        }).start();

        new Thread(() -> {
            test.test4();
        }).start();
        */
        //
        //new Thread(() -> {
        //    Test.testStatic();
        //    Test.testStatic();
        //}).start();
        //
        //new Thread(() -> {
        //    Test.testStatic();
        //}).start();
    }

    public void test() {
        synchronized (this) {
            try {
                System.out.println("test()...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void test2() {
        synchronized (this) {
            try {
                System.out.println("test2()...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized static void testStatic() {
        try {
            System.out.println("testStatic()...");
            testStatic2();
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized static void testStatic2() {
        try {
            System.out.println("testStatic2()...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

        // 非静态方法锁this
    public synchronized void test3() {
        try {
            System.out.println("test3()...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void test4() {
        try {
            System.out.println("test4()...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
